// 技能共享发布页面逻辑
const NeighborhoodAPI = require('../../../js/services/api/neighborhoodService');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      skillName: '',
      skillDesc: '',
      contactInfo: '',
      serviceTime: ''
    },
    errors: {},
    categoryOptions: ['生活服务', '教育培训', '维修服务', '咨询服务', '其他技能'],
    selectedCategory: -1,
    serviceMethod: 'both',
    storeVerification: true,
    isSubmitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('页面加载 - 技能发布');
    wx.setNavigationBarTitle({
      title: '发布技能共享'
    });
    this.initFormData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('页面显示 - 技能发布');
    this.initFormData();
  },

  /**
   * 初始化表单数据
   */
  initFormData: function() {
    // 确保数据正确初始化
    this.setData({
      formData: {
        skillName: '',
        skillDesc: '',
        contactInfo: '',
        serviceTime: ''
      },
      errors: {},
      selectedCategory: -1,
      serviceMethod: 'both',
      storeVerification: true,
      isSubmitting: false
    });
    
    console.log('技能发布页面数据初始化完成:', this.data);
  },

  /**
   * 输入框变化处理
   */
  onInputChange: function(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    console.log('输入变化:', field, value);
    
    this.setData({
      [`formData.${field}`]: value
    });
    
    // 清除对应字段的错误信息
    if (this.data.errors[field]) {
      this.setData({
        [`errors.${field}`]: ''
      });
    }
  },

  /**
   * 选择技能类别
   */
  onCategoryChange: function(e) {
    this.setData({ selectedCategory: e.detail.value });
    
    // 清除错误信息
    if (this.data.errors.skillCategory) {
      this.setData({
        'errors.skillCategory': ''
      });
    }
  },

  /**
   * 选择服务方式
   */
  onServiceMethodChange: function(e) {
    this.setData({ serviceMethod: e.detail.value });
    
    // 清除错误信息
    if (this.data.errors.serviceMethod) {
      this.setData({
        'errors.serviceMethod': ''
      });
    }
  },

  /**
   * 切换门店审核状态
   */
  onStoreVerificationChange: function(e) {
    this.setData({ storeVerification: e.detail.value });
  },

  /**
   * 表单验证
   */
  validateForm: function() {
    const errors = {};
    const { formData, selectedCategory, serviceMethod } = this.data;
    
    if (!formData.skillName.trim()) {
      errors.skillName = '请输入技能名称';
    }
    
    if (selectedCategory < 0) {
      errors.skillCategory = '请选择技能类别';
    }
    
    if (!formData.skillDesc.trim()) {
      errors.skillDesc = '请描述技能内容';
    } else if (formData.skillDesc.trim().length < 10) {
      errors.skillDesc = '技能描述至少10个字符';
    }
    
    if (!serviceMethod) {
      errors.serviceMethod = '请选择服务方式';
    }
    
    if (!formData.contactInfo.trim()) {
      errors.contactInfo = '请输入联系方式';
    } else if (!/^1[3-9]\d{9}$/.test(formData.contactInfo)) {
      errors.contactInfo = '请输入正确的手机号码';
    }
    
    this.setData({ errors });
    return Object.keys(errors).length === 0;
  },

  /**
   * 提交技能信息
   */
  submitSkill: function(e) {
    if (this.data.isSubmitting) return;

    // 表单验证
    if (!this.validateForm()) {
      return;
    }

    this.setData({ isSubmitting: true });

    // 构建提交数据
    const skillData = {
      name: this.data.formData.skillName.trim(),
      category: this.data.categoryOptions[this.data.selectedCategory],
      description: this.data.formData.skillDesc.trim(),
      serviceMethod: this.data.serviceMethod,
      contactInfo: this.data.formData.contactInfo.trim(),
      serviceTime: this.data.formData.serviceTime.trim(),
      needStoreVerification: this.data.storeVerification,
      status: this.data.storeVerification ? 'pending_approval' : 'published'
    };

    NeighborhoodAPI.publishSkill(skillData)
      .then(res => {
        if (res.success) {
          wx.showToast({
            title: this.data.storeVerification ? '技能提交成功，等待门店审核' : '技能发布成功',
            icon: 'success',
            duration: 2000
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        } else {
          wx.showToast({ title: res.message || '发布失败', icon: 'none' });
        }
      })
      .catch(err => {
        console.error('技能发布失败:', err);
        wx.showToast({ title: '网络异常，发布失败', icon: 'none' });
      })
      .finally(() => {
        this.setData({ isSubmitting: false });
      });
  }
});